package util;

import java.io.IOException;
import java.io.Serializable;
import java.util.Comparator;
import util.Configuration;

/**
 * Comparator class for sorting contestants by 1) class 2) within stipulated
 * time 3) total laps 4) total time
 * 
 * @author team07
 * 
 */
public class SortByPosition implements Comparator<Contestant>, Serializable {

	private static final long serialVersionUID = -162951201850954821L;
//	public static final long MAXTIME = 3600 * 1000;
	public long maxtime;
	
	
	public SortByPosition(){
		 try {
			maxtime = Long.valueOf(Configuration.get(Configuration.MAXTIME));
		} catch (NumberFormatException e) {
			maxtime = 1;
		} catch (IOException e) {
			//Hit kommer vi aldrig
		}
		//Multiplicera upp maxtiden till millisekunder
		maxtime *= 60*1000;
	}
	
	/**
	 * Returns the int-value for sorting regarding: 1) class 2) within
	 * stipulated time 3) total laps 4) total time
	 * 
	 * @param c1
	 *            A Contestant
	 * @param c2
	 *            A Contestant
	 * @return Negative int if Contestant c1 fulfills the pos-criterias and vice
	 *         versa
	 */
	public int compare(Contestant c1, Contestant c2) {
		int points = 0;

		if (c1.getTotalTime() < maxtime)
			points += 4;
		if (c2.getTotalTime() < maxtime)
			points -= 4;

		if (c1.getNbrParts() != c2.getNbrParts())
			points += c1.getNbrParts() < c2.getNbrParts() ? 2 : -2;

		if (c1.getTotalTime() != c2.getTotalTime())
			points += c1.getTotalTime() > c2.getTotalTime() ? 1 : -1;

		return points;
	}
}